package com.pms.utils;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by 小脸通红 on 9/19/15.
 */
public class Base64Helper {
    private static String Base64ExcelHeader03 = "data:application/vnd.ms-excel;base64,(.*)";
    private static String Base64ExcelHeader07 = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,(.*)";

    public static byte[] getExcelFromBASE64(String fileData) throws Exception {
        try {
            if(fileData == null)
                throw new Exception("文件数据不正确") ;
            if(!fileData.matches(Base64ExcelHeader03) && !fileData.matches(Base64ExcelHeader07))
                throw new Exception("文件格式不正确") ;
            fileData = fileData.substring(fileData.indexOf(',') + 1);
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] decoderBytes = decoder.decodeBuffer(fileData);
            return decoderBytes;

        } catch (Exception e) {
            throw e;
        }
    }

    public static String getExcelFromBASE64(String path, String fileData) throws Exception {
        if (fileData == null)
            throw new Exception("文件数据不正确");
        if (!fileData.matches(Base64ExcelHeader03))
            throw new Exception("文件格式不正确");
        fileData = fileData.substring(fileData.indexOf(',') + 1);

        File file = new File(getRelativelyPath() + path);
        if (!file.exists()) {
            file.mkdir();
        }

        String fileName = UUID.randomUUID().toString();
        String pathName = getRelativelyPath() + path + fileName;
        BASE64Decoder decoder = new BASE64Decoder();
        FileOutputStream write = new FileOutputStream(new File(pathName));
        byte[] decoderBytes = decoder.decodeBuffer(fileData);
        write.write(decoderBytes);
        write.close();

        return path + fileName;
    }

    public static boolean matchesFile(String fileData) {
        if (fileData.matches(Base64ExcelHeader03))
            return true;
        if (fileData.matches(Base64ExcelHeader07))
            return true;
        return false;
    }


    public static String getRelativelyPath() {

        try {
            String cp = new File(Base64Helper.class.getResource("/").getFile()).getParentFile().getCanonicalPath();
            cp = cp.substring(0, cp.length() - 7);
            return cp;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ".";
    }
}
